package com.example.bootdemo.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import javax.annotation.Resource;

@Configuration
public class RedisConfig {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory,
            MessageListener messageListener) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        // 设置监听的频道，这里监听了"__keyevent@0__:expired"频道，其中0是Redis数据库的索引
        container.addMessageListener(messageListener, new PatternTopic("__keyevent@*__:expired"));

        return container;
    }

   /* @Bean
    RedisMessageListenerContainer container() {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        // 订阅所有db的过期事件
        container.addMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                String expiredKey = message.toString();
                System.out.println(expiredKey);
                if (expiredKey.startsWith("order:")) {
                    // 处理订单超时逻辑
                    String orderId = expiredKey.split(":")[1];
                    System.out.println("orderId::"+orderId);
                    // 这里调用你的服务类方法，处理订单超时逻辑
                    // orderService.cancelOrder(orderId);
                }
            }
        }, new PatternTopic("__keyevent@*__:expired"));
        return container;
    }*/
}
